﻿using System;
using System.Reactive;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using ReactiveUI;

namespace MilkTeaMachine.OfflineClient.ViewModels;

public class MainPageViewModel : ViewModelBase, IRoutableViewModel
{
    public MainPageViewModel(IScreen hostScreen)
    {
        Console.WriteLine(nameof(MainPageViewModel) + " initialized");
        HostScreen = hostScreen;
        GoAutoRunningScanOrder =
            ReactiveCommand.CreateFromObservable(() =>
                HostScreen.Router.Navigate.Execute(new AutoRunningScanOrderViewModel(hostScreen)));
        GoFormulaSetting =
            ReactiveCommand.CreateFromObservable(() =>
                HostScreen.Router.Navigate.Execute(new FormulaInputViewModel(hostScreen)));
        GoProgramSettingCmd =
            ReactiveCommand.CreateFromObservable(() =>
                HostScreen.Router.Navigate.Execute(new IngredientCalibrationSelectorViewModel(HostScreen)));
        ExitApplicationCmd = ReactiveCommand.Create(ExitApplication);
    }

    private void ExitApplication()
    {
        if (Application.Current?.ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop)
        {
            return;
        }

        desktop.Shutdown();
    }

    public MainPageViewModel() : this(default!)
    {
    }

    public string? UrlPathSegment { get; } = nameof(MainPageViewModel);
    public IScreen HostScreen { get; }
    public ReactiveCommand<Unit, IRoutableViewModel> GoAutoRunningScanOrder { get; }
    public ReactiveCommand<Unit, IRoutableViewModel> GoFormulaSetting { get; }
    public ReactiveCommand<Unit, IRoutableViewModel> GoProgramSettingCmd { get; }
    public ReactiveCommand<Unit, Unit> ExitApplicationCmd { get; }
}